const {
    json
} = require('express')
const fs = require('fs')
const mysql = require('mysql')
const path = require('path')

const Controller_content = {}

//导入模块
const dbQuery = require('../model/model.js')

const {
    getUnixTime
} = require('../util/tool')

//  审核状态
let statusTextMap = {
    0: '<span class="c-gray">待审核</span>',
    1: '<span class="c-green">审核通过</span>',
    2: '<span class="c-red">审核失败</span>'
}

//首页
Controller_content.index = (req, res) => {
    // 1. 编写sql语句
    let userInfo = JSON.parse(req.session.userInfo);
    // //连表  指定  排序 
    // let sql = `select t1.*,t2.name from article t1 left join articletable 
    //     t2 on t1.sort = t2.id where is_delete = 0 order by id desc`
    // // 2. 执行sql
    // dbQuery(sql).then(result => {
    //     let data = result.map((item) => {
    //         item.Audit_status = statusTextMap[item.Audit_status]
    //         return item;
    //     })
    // console.log(data)
    // 3. 把查询出来的数据分配到模板引擎中
    // if(userInfo.account_number =="陈鉴彪123"){
    //     userInfo.account_number="伟大的陈鉴彪"
    // }
    res.render('Articlepage.html', {
        // articles: data,
        userInfo
    })
}

//文章回收
Controller_content.recyclelist = (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    // 1. 编写sql语句
    let sql = `select t1.*,t2.name from article t1 
    left join Articletable t2 on t1.sort = t2.id 
     where t1.Audit_status =1  and t1.is_delete = 1 order by t1.id desc`;
    //执行slq
    dbQuery(sql).then(result => {
        let data = result.map((item) => {
            item.Audit_status = statusTextMap[item.status]
            return item;
        })
        res.render('recycle.html', {
            articles: data,
            userInfo
        })
    })
}

//  4 文章删除
Controller_content.delete = (req, res) => {
    //1. 接受要删除的文章的id
    let {
        id,
        img
    } = req.query;

    //2. 编写sql语句，删除
    let sql = `delete from article where id = ${id}`;
    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            if (img) {
                let oldpath = path.join(__dirname, '../', img)
                fs.unlink(oldpath, (err) => {

                })
            }
            // 删除成功 ，重定向到首页
            res.redirect('Articlepage')
        } else {
            // 删除失败，响应js代码，让浏览器执行
            res.send("<script>alert('删除失败'); location.href = '/'; </script>")
        }
    })

}


//   ajax文章删除
Controller_content.ajaxdelete = (req, res) => {
    //1. 接受要删除的文章的id
    let {
        id,
        img
    } = req.body;
    //2. 编写sql语句，删除
    let sql = `delete from article where id = ${id}`;
    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            if (img) {
                let oldpath = path.join(__dirname, '../', img)
                fs.unlink(oldpath, (err) => {

                })
            }
            res.json({
                code: 20000,
                message: "succes"
            })

        } else {
            res.json({
                code: -1,
                message: "fial"
            })
        }
    })

}

// 5 文章添加
Controller_content.add = (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    // 取出所有的分类数据分配到模板中
    let sql = "select * from articletable";
    dbQuery(sql).then(result => {
        res.render('add.html', {
            cats: result,
            userInfo
        })
    })
}

// 实现数据添加入库 
Controller_content.insert = (req, res) => {
    // console.log(req.body);
    // console.log(req.file);
    //判断是否有图片
    let imgPath = '';
    if (req.file) {
        let {
            originalname,
            filename,
            destination
        } = req.file
        let ext = originalname.substring(originalname.indexOf('.'));

        let oldpath = path.join(__dirname, "../", destination, filename);
        let newPath = path.join(__dirname, "../", destination, filename) + ext;
        imgPath = `${destination}${filename}${ext}`
        fs.renameSync(oldpath, newPath)
    }
    // 1.接受post参数
    let {
        title,
        author,
        cat_id,
        content,
        AudIt_status
    } = req.body
    let nowTime = getUnixTime();
    //  第一个（）中的字段是设计表中的字段，第二个（）是前端传过来字段
    let sql = `insert into article(title,img,author,content,sort,Audit_status,Update_time)values
    ("${title}","${imgPath}","${author}","${content}","${cat_id}","${AudIt_status}","${nowTime}")`;
    // let bind = [title,imgPath,author,content,cat_id,AudIt_status,nowTime]

    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            res.send("<script>alert('成功');location.href='/';</script>")
        } else {
            res.send("<script>alert('失败');location.href='/add';</script>")
        }
    })
}

//  实现编辑文章页面的回显操作
Controller_content.edit = (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    // console.log(userInfo) //有数据
    let {
        id,
    } = req.query;
    // console.log(req.query)//有数据
    // 查询指定条件
    let sql = `select * from article where id=${id}`;
    dbQuery(sql).then(result => {
        let sql2 = 'select * from articletable';
        dbQuery(sql2).then(result2 => {
            res.render('edit.html', {
                articles: result[0],
                sort: result2,
                userInfo
            })

        })
    })
}

// 实现文章编辑入库操作
Controller_content.update = (req, res) => {

    let {
        id,
        title,
        author,
        Audit_status,
        sort,
        content
    } = req.body
    // console.log(req.body)

    let Update_time = getUnixTime();

    let sql = `update article set title ="${title}",author ="${author}",Audit_status ="${Audit_status}",sort ="${sort}",content ="${content}",Update_time ="${Update_time}" where id ="${id}"`
    dbQuery(sql).then(result => {
        if (result.affectedRows) {
            // console.log(result.affectedRows)
            res.redirect('/Articlepage')
        } else {
            res.send('<script>alert("编辑失败");location.href="/";<script>')
        }
    })
}

//实现文章加入回收站
Controller_content.recycle = (req, res) => {
    let {
        id
    } = req.query
    $sql = `update article set is_delete = 1 where id =${id}`;
    //执行
    dbQuery($sql).then(result => {
        let {
            affectedRows
        } = result;
        //判断剩余行数
        if (affectedRows) {
            res.redirect('/Articlepage')
        } else {
            res.send("<script>alert(加入失败);location.href='/'</script>")

        }
    })
}

//实现文章还原
Controller_content.restore = (req, res) => {
    let {
        id
    } = req.query
    $sql = `update article set is_delete = 0 where id = ${id}`;
    dbQuery($sql).then(result => {
        let {
            affectedRows
        } = result;
        if (affectedRows) {
            res.redirect('/Articlepage')
        } else {
            res.send("<script>alert('还原失败');location.href='/';</script>")
        }
    })
}

//展示一个上传文件的表单
Controller_content.addImg = (req, res) => {
    res.render('addimg.html')
}

//处理文件上传
Controller_content.upload = (req, res) => {
    // console.log(req.file); // 接收二进制数据
    // console.log(req.body); 
    let {
        originalname,
        filename,
        destination
    } = req.file

    let ext = originalname.substring(originalname.indexOf('.'));

    let oldpath = path.join(__dirname, destination, filename);
    let newPath = path.join(__dirname, destination, filename) + ext;
    fs.renameSync(oldpath, newPath)

    res.send('upload success')
}

//文章详情
Controller_content.detail = (req, res) => {
    let {
        id
    } = req.query;
    // console.log(id)
    let sql = `select * from article where id = ${id}`
    dbQuery(sql).then(result => {

        res.render('detail.html', {
            a: result[0]
        })

    })

}

// 给文章添加内容展示视图
Controller_content.editContent = (req, res) => {
    let userInfo = json.parse(req.session.userInfo || '{}')
    res.render('editContent.html', {
        userInfo
    })
}

//编辑文章
Controller_content.updateArtilceContent = async (req, res) => {

    let {
        id,
        content
    } = req.body;
    let sql = `update articletable set content  = '${content}' where id =  '${id}'`
    let result = await dbQuery(sql)
    res.json({
        code: 20000,
        message: '编辑文章OK'
    })
}

//分类数据
// Controller_content.paging = async (req, res) => {
//     let {curr = 1, limit = 10,title,Audit_status} = req.query;
//     //p判断是否有查询条件
//     let where= '';
//     if(title){
//         where +=`and title like '%${title}%'`
//     }
//     //查询状态
//     if(Audit_status){
//         where += `and  Audit_status =%${Audit_status}%`
//     }
//     let sql = `select count(*) as count from article where 1 and is_delete = 0  ${where}` ;

//     //分页原理 当前页 - 1
//     let offset = (curr - 1) * limit;
//     //order by t1.id 
//     let sql2 = `select t1.*,t2.name from article t1
//      left join Articletable t2 on t1.sort = t2.id 
//      where 1 and is_delete = 0 ${where}
//      order by t1.id desc
//      limit ${offset},${limit}`;

//     let result = await Promise.all([dbQuery(sql),dbQuery(sql2)])

//     res.json({
//         count: result[0][0].count,
//         data: result[1],

//     })



// }




//文章数据
Controller_content.paging = async (req, res) => {
    // console.log(111)
    // console.log(req.query);
    let {
        curr = 1, limit = 10, title, Audit_status
    } = req.query; // 1   10
    // 判断是否有查询条件
    let where = '';
    if (title) {
        where += ` and title like '%${title}%'`
    }

    if (Audit_status) {
        where += ` and Audit_status = ${Audit_status}`
    }
    // 查询文章总记录数
    let sql = `select count(*) as count from article where 1 and  is_delete = 0  ${where}`;


    // let result = await queryPromise(sql)
    let offset = (curr - 1) * limit;

    // 查询分页数据
    let sql2 = `select t1.*,t2.name from article  as t1 
                     left join Articletable t2 on t1.sort = t2.id 
                     where 1 and  is_delete = 0 ${where}
                     order by t1.id desc 
                     limit ${offset},${limit}`;
    let promise1 = dbQuery(sql)
    let promise2 = dbQuery(sql2)

    // let result2 = await queryPromise(sql2)
    // 并行 
    let result = await Promise.all([promise1,promise2])
    // console.log(result);
    // console.log(result); // [[{count:50}],[{},{},{}]]
    res.json({
        count: result[0][0].count,
        data: result[1]
    })

}


//首页分类数据表
Controller_content.ClassificationDataSheet  = async(req,res)=>{
    let sql = `select t2.name,count(t1.sort) as count from article t1 left join articletable t2 on t1.sort = t2.id group by t1.sort`
   let result = await dbQuery(sql)
    res.json(result)
    // console.log(result)
}
module.exports = Controller_content